import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, R, Divider, Tag, Row, Col, Input } from 'antd';
import '@/assets/css/settings';
import * as BomService from '../../axios/Bom'
import * as APIService from '../../axios/api';
import { BasicLayout, BasicLayoutSearch } from '../../components/BasicLayout';
import { BasicPagination, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../components/TableCustomize'
import { withPermission } from '../../components/withpermission';
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import { withRouter } from 'react-router';
const PhdbButton = withPermission(Button, 'phdb')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')
class Bom extends Component {
	state = {
		dataSource: [],
		visible: false,
		advanced: false,
		searchItem: {},
		modalTitle: '新增',
		formData: {},
		drawerVisible: false,
		drawerVisible1: false,
		drawerTitle: '清单导入',
		pageSize: 10,
		pageNum: 1,
		total: 40,
		columns: [
			{
				title: '序号',
				dataIndex: 'id',
				width: 50,
				align: 'center',
				render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>,
			},

			{
				title: '机型',
				width: 180,
				dataIndex: 'model',
				sorter: (a, b) => compareString(a.model, b.model)
			},
			{
				title: '批号',
				width: 100,
				dataIndex: 'batchNo',
				sorter: (a, b) => compareString(a.batchNo, b.batchNo)
			},
			{
				title: '装配部门',
				width: 130,
				dataIndex: 'workShopCode',
				sorter: (a, b) => compareString(a.workShopCode, b.workShopCode)
			},
			{
				title: '当前版本号',
				width: 110,
				dataIndex: 'version',
				sorter: (a, b) => compareString(a.version, b.version)
			},
			{
				title: '数据来源',
				width: 80,
				dataIndex: 'importFrom',
				render: (text) => text === '1' ? '文件导入' : text === '2' ? 'ERP接口' : ''
			},
			{
				title: '标准件',
				width: 80,
				dataIndex: 'isStandardImport',
				render: (text) => text === '1' ? <Tag color="cyan">已导入</Tag> : text === '0' ? <Tag color="red">未导入</Tag> : ''
			},
			{
				title: '零件',
				width: 80,
				dataIndex: 'isPartImport',
				render: (text) => text === '1' ? <Tag color="cyan">已导入</Tag> : text === '0' ? <Tag color="red">未导入</Tag> : ''
			},
			{
				title: '配件',
				width: 80,
				dataIndex: 'isFittingImport',
				render: (text) => text === '1' ? <Tag color="cyan">已导入</Tag> : text === '0' ? <Tag color="red">未导入</Tag> : ''
			},
			{
				title: '周边物料',
				width: 80,
				dataIndex: 'isAroundImport',
				render: (text) => text === '1' ? <Tag color="cyan">已导入</Tag> : text === '0' ? <Tag color="red">未导入</Tag> : ''
			},
			{
				title: '创建时间',
				width: 150,
				dataIndex: 'createTime',
			},
			{
				title: '操作',
				width: 150,
				dataIndex: 'opts',
				render: (text, record) =>
					<div>
						<a onClick={() => this.openDetails(record)}>详细数据</a>
						<Divider type="vertical" />
						<a onClick={() => this.deletes(record)}>删除</a>
					</div>

			},
			{ dataIndex: '999' }
		],
		// fileList: [[], [], [], [], []]
		fileList: [[], [], [], []],
		submitLoading: false,
		modelList: [],
		BomService: false,
		selectedRows: [],
		selectedRowKeys: [],
		options: [],
	};
	componentDidMount() {
		// console.log(this.props.location.data)
		this.modelList();
		if (this.props.location.data) {
			this.setState({ searchItem: this.props.location.data }, this.fetch)
		} else {
			this.fetch()
		}
	}
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	//初始化加载数据
	fetch = (pageNum = 1, pageSize = 100) => {
		this.setState({ loading: true });
		const { searchItem } = this.state;
		searchItem.pageNum = pageNum;
		searchItem.pageSize = pageSize;
		BomService.productionOrderImportList(searchItem).then(res => {
			this.setState({ loading: false })
			if (res.data.code !== 200) {
				openModalMessage('warning', res.data.msg);
				return;
			}
			this.setState({ dataSource: res.data.data, total: res.data.total, pageNum, pageSize });
		}).catch(err => {
			openModalMessage('error', err.message);
		})
	}
	modelList = () => {
		BomService.modelList().then(res => {
			let data = [];
			if (res.data.code === 200) {
				data = res.data.data && res.data.data.length ? res.data.data : [];
			}
			this.setState({ modelList: data })
		})
	}
	// 删除
	deletes = (data) => {
		let id = `id=${data.id}`
		let then = this
		Modal.confirm({
			title: '确认删除当项吗，这将影响其他数据模块?',
			onOk() {
				BomService.deleteBatchBom(id).then((item) => {
					if (item.data.code === 200) {
						openSuccessModal('删除成功')
						then.fetch()
						return
					}
					openModalMessage('error', item.data.msg)
				})
			},
			onCancel() {
			},
		})

	}
	onHandleOk = () => {
		this.formDrawer.validateFields((err, value) => {
			if (err) return;
			console.log(value, 'value');
			value.departmentId = value.departmentId === undefined ? 0 : value.departmentId[value.departmentId.length - 1];
			this.setState({ submitLoading: true })
			let arr1 = {
				batchNo: value.batchNo,
				model: value.model,
				userId: localStorage.getItem('userId'),
				departmentId: value.departmentId
			}
			console.log(arr1, 'arr1');
			let files = this.state.fileList;
			console.log(files, 'files---------');
			let names = ['标准件', '零件', '配件', '周边物料', '车间'];
			let newFiles = [];
			for (var key in files) {
				if (files[key].length) {
					const name = files[key][0].name;
					if (name.indexOf(`${names[key]}`) === -1) {
						openModalMessage('warning', '请核对文件名！');
						this.setState({ submitLoading: false });
						return;
					}
					newFiles.push(files[key])
				}
			}
			if (!newFiles.length) {
				openModalMessage('warning', '请至少上传一个文件！');
				this.setState({ submitLoading: false });
				return;
			}
			const data = new window.FormData();
			// 拼接文件名
			// for (let i in files) {
			// 	let item = files[i]
			// 	if (item.length) {
			// 		let arr = item[0].name.split('.xls')
			// 		let typeName = '-' + names[i]
			// 		let fileName = arr[0] + typeName + '.xls' + arr[1]
			// 		data.append('files', item[0], fileName);
			// 	}
			// }

			for (var item of files) {
				if (item.length) {
					data.append('files', item[0]);
				}
			}
			BomService.addOrUpdate(JSON.stringify(arr1), data).then(res => {
				// console.log(res)
				this.setState({ submitLoading: false });
				if (res.data.code !== 200) {
					openModalMessage('warning', res.data.msg);
					return;
				}
				localStorage.setItem('BomServiceID', res.data.data)
				openSuccessModal(res.data.msg);
				this.setState({
					BomService: true
				}, () => {
					localStorage.setItem('BomService', this.state.BomService)
				})
				this.handleCancel()
			}).catch(err => {
				openModalMessage('error', err.message);
				this.setState({ submitLoading: false });
			})
		})
	}
	showDrawer = () => {
		APIService.getDepartMents().then((data) => {
			const dataSource = data.data.data;
			const options = [];
			for (var value of dataSource) {
				var json = { "label": value.name, "value": value.id, 'children': [] }

				if (value.children.length !== 0) {
					for (var valueFirst of value.children) {
						var json2 = { "label": valueFirst.name, "value": valueFirst.id, 'children': [] }
						// if (valueFirst.children.length !== 0) {
						// 	for (var valueSecond of valueFirst.children) {
						// 		json2.children.push({ 'label': valueSecond.name, 'value': valueSecond.id })
						// 	}
						// }
						json.children.push(json2)
					}
				}
				options.push(json);
			}

			const { selectedRows } = this.state
			let formData = {}
			if (selectedRows.length > 0) {
				for (let i in selectedRows) {
					if (i == 0) {
						formData = selectedRows[i]
					}
				}
			}
			console.log(formData, 'formData');

			this.setState({
				formData,
				options: options,
				drawerVisible: true,
			})
		}
		)


	}
	showDrawer1 = () => {
		this.setState({
			drawerVisible1: true,
		});
	}
	// 模板导出
	exportExcelDemo1 = () => {
		BomService.exportExcelDemo1().then((res) => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('标准件');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	exportExcelDemo2 = () => {
		BomService.exportExcelDemo2().then((res) => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('零件');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	exportExcelDemo3 = () => {
		BomService.exportExcelDemo3().then((res) => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('周边物料');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	exportExcelDemo4 = () => {
		BomService.exportExcelDemo4().then((res) => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('配件');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	exportImportList = () => {
		const { dataSource } = this.state
		// console.log(dataSource);
		Modal.confirm({
			title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
			onOk() {
				BomService.exportImportList({ dataSource: dataSource }).then((res) => {
					//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
					let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
					// 创建A标签
					let link = document.createElement('a')
					link.style.display = 'none'
					link.href = url
					// 设置的下载文件文件名
					const fileName = decodeURI('生产订单BOM');
					// 触发点击方法
					link.setAttribute('download', fileName)
					document.body.appendChild(link)
					link.click()
				})
			},
			onCancel() { },
		});

	}
	handleCancel = e => {
		this.formDrawer && this.formDrawer.resetFields();
		this.setState({
			drawerVisible: false,
			// fileList: [[], [], [], [], []]
			fileList: [[], [], [], []]
		});
		this.fetch();
	};


	handleSearch = value => {
		// console.log(value)
		if (value.createTimeStart) {
			value.createTimeStart = value.createTimeStart.format('YYYY-MM-DD')
		}
		this.setState({ searchItem: value }, this.fetch);
	};

	onHandleAdvanced = () => {
		this.setState({ advanced: !this.state.advanced })
	}
	saveFileList = (index, value) => {
		const { fileList } = this.state;
		fileList[index] = value;
		this.setState({ fileList })
		// console.log('这是什么', fileList)
	}
	// 打开详情页
	openDetails = (record) => {
		const { searchItem } = this.state;
		// const data = { id: record.id, batchNo: record.batchNo, version: record.version }
		const data = { ...record }
		localStorage.setItem('Bom_searchItem', JSON.stringify(searchItem));
		localStorage.setItem('Bom_detailsList', JSON.stringify(data));
		this.props.history.push({ pathname: "/Bom_details", data: { record: data, searchItem } })
	}
	resetForm = () => {
		this.formSearch && this.formSearch.resetFields();
		this.setState({ searchItem: {} }, this.fetch);
	}
	BatchNumberComparison = () => {
		const { selectedRows } = this.state
		if (selectedRows[0] === undefined) {
			openModalMessage('warning', '请选择要对比的两项数据！！');
			return
		}
		if (selectedRows.length !== 2) {
			openModalMessage('warning', '请勾选两项！！');
			return
		}
		for (let index = 0; index < selectedRows.length; index++) {
			for (let i = index + 1; i < selectedRows.length; i++) {
				if (selectedRows[index].model === selectedRows[i].model) {
					console.log('比较数据', selectedRows);
					localStorage.setItem('ComparisonBatchNumber', JSON.stringify(selectedRows))
					this.props.history.push({ pathname: '/ComparisonBatchNumber', data: { compare: selectedRows } })
					return
				}
				openModalMessage('warning', '请选择相同机型！！');
			}

		}

	}
	componentWillUnmount() {
		this.setState({
			BomService: false
		})
	}
	render() {
		const { selectedRowKeys, loading, dataSource, formData, drawerVisible, drawerTitle, advanced, columns, pageNum, pageSize, total, searchItem, submitLoading, modelList } = this.state;
		const rowSelection = {
			type: 'checkbox',
			columnWidth: 40,
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				// console.log(selectedRows);
				this.setState({
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys,
				})
			},
		}
		const { form: { getFieldDecorator } } = this.props
		return (
			<div>
				<BasicLayoutSearch>
					<SearchForm onSearch={this.handleSearch}
						onClick={this.onHandleAdvanced}
						advanced={advanced}
						searchItem={searchItem}
						resetForm={this.resetForm}
						ref={node => (this.formSearch = node)}
						modelList={modelList}
					/>
				</BasicLayoutSearch>
				<BasicLayout buttons={[
					<PhdbButton key={1} onClick={this.BatchNumberComparison} />,
					<DownLoadButton key={2} onClick={this.exportExcelDemo1} icon='download' text='标准件模板' />,
					<DownLoadButton key={3} onClick={this.exportExcelDemo2} icon='download' text='零件模板' />,
					<DownLoadButton key={4} onClick={this.exportExcelDemo3} icon='download' text='周边物料模板' />,
					<DownLoadButton key={5} onClick={this.exportExcelDemo4} icon='download' text='配件模板' />,
					<DownLoadButton key={6} onClick={this.exportImportList} icon='download' text='导出' />,
					<UploadButton key={7} onClick={this.showDrawer} icon='upload' />

					// <Button key={7} onClick={this.BatchNumberComparison} type='primary'>批号对比</Button>,
					// <Button key={3} onClick={this.exportExcelDemo1} type='primary' icon='download'>标准件模板</Button>,
					// <Button key={4} onClick={this.exportExcelDemo2} type='primary' icon='download'>零件模板</Button>,
					// <Button key={5} onClick={this.exportExcelDemo3} type='primary' icon='download'>周边物料模板</Button>,
					// <Button key={6} onClick={this.exportExcelDemo4} type='primary' icon='download'>配件模板</Button>,
					// <Button key={1} onClick={this.exportImportList} type='primary' icon='download'>导出</Button>,
					// <Button key={2} onClick={this.showDrawer} type='primary' icon='upload'>导入</Button>
				]} name="生产订单（Bom）" icon="table"
				>
					<TableCustomize
						columns={columns}
						rowKey={(record) => record.id}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						allowRowEdit
						rowSelection={rowSelection}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
						}}
					/>
					<BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
				</BasicLayout>

				<Drawer width={460} visible={drawerVisible} title={drawerTitle} onClose={this.handleCancel}
					maskClosable={false}
					destroyOnClose={true}>
					<AddForm
						formData={formData}
						onOk={this.onHandleOk}
						ref={node => (this.formDrawer = node)}
						onClose={this.handleCancel}
						saveFileList={this.saveFileList}
						modelList={modelList}
						options={this.state.options}
					/>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
						<Button type="primary" onClick={this.onHandleOk} loading={submitLoading}>
							{'确认'}
						</Button>
					</div>

				</Drawer>
			</div>
		);
	}
}
export default Form.create()(withRouter(Bom));